/*****
 * 店铺搜索组件
 */

import { useEffect, useMemo, useState } from "react";
import { Select, Input, Tooltip, Checkbox } from "antd";
import { SearchOutlined, RightOutlined, DownOutlined } from '@ant-design/icons';
import Iconfont from '@/components/IconFont';
import SetShop from "./SetShop";
import { platformTypeName } from '@/utils/config';
import { remove } from "lodash";
import styles from './index.module.less';
import api from './service.js';

export default (props) => {

	const { changeId, storeIds = [], handleOk, style={} } = props;

	//当前选择的数据
	const [selectKeys, setSelectKeys] = useState([]);

	//用于模糊搜索的输入框
	const [searchStr, setSearchStr] = useState();

	//原始数据
	const [storeData, serStoreData] = useState({});

	//控制设置弹框显隐
	const [visible, setVisible] = useState(false);

	//控制下拉框是否展示
	const [open, setOpen] = useState(false);

	//控制分组展开和关闭
	const [openGroup, setOpenGroup] = useState({});

	useEffect(() => {
		getShopList();
	}, [])

	//每次重新请求以后重新赋值
	useEffect(() => {
		setSelectKeys(storeIds);
	}, [changeId])

	useEffect(() => {
		handleOk(selectKeys);
	}, [selectKeys])

	//请求列表数据
	const getShopList = async () => {
		const { success, data } = await api.queryShopGroups({
			type: '1'
		})
		if (success) {
			serStoreData(data);
		}
	}

	//点击打开设置弹框
	const openShopSet = () => {
		setOpen(false);
		setVisible(true);
	}

	//控制下拉框显示隐藏
	const handleVisibleChange = val => {
		setOpen(val);
	}

	//点击选择店铺
	const selectStore = (e, id) => {
		const checked = e.target.checked;
		const arr = [...selectKeys];
		if (checked) {
			arr.push(id);
		} else {
			remove(arr, v => v == id);
		}
		setSelectKeys(arr);
	}

	//点击全选或者取消全选组
	const checkGroupAll = (e, arr) => {
		const checked = e.target.checked;
		const list = [...selectKeys];
		if (checked) {
			arr.map(v => {
				if (!list.includes(v.ecStoreId)) {
					list.push(v.ecStoreId);
				}
			})
		} else {
			arr.map(v => {
				remove(list, val => val == v.ecStoreId);
			})
		}
		setSelectKeys(list);
	}

	//模糊搜索用于最终展示的数据
	const formatStoreData = useMemo(() => {
		if (searchStr) {
			const { ecStoreSearchGroupList = [], unGroupedEcStore = [] } = storeData;

			const arr = [];
			for (let i in ecStoreSearchGroupList) {
				if (ecStoreSearchGroupList[i].ecStoreSearchDetailList.length > 0) {
					const list = ecStoreSearchGroupList[i].ecStoreSearchDetailList;
					const obj = {
						...ecStoreSearchGroupList[i],
						ecStoreSearchDetailList: []
					};
					for (let j in list) {
						if (list[j].storeName.includes(searchStr)) {
							obj.ecStoreSearchDetailList.push(list[j]);
						}
					}
					if (obj.ecStoreSearchDetailList.length > 0) {
						arr.push(obj);
					}
				}
			}
			const arr1 = [];
			for (let i in unGroupedEcStore) {
				if (unGroupedEcStore[i].storeName.includes(searchStr)) {
					arr1.push(unGroupedEcStore[i]);
				}
			}
			return {
				ecStoreSearchGroupList: arr,
				unGroupedEcStore: arr1,
			};
		} else {
			return storeData;
		}
	}, [storeData, searchStr])

	const { ecStoreSearchGroupList = [], unGroupedEcStore = [] } = formatStoreData;

	//店铺默认提示信息
	const placeholder = useMemo(() => {
		if (selectKeys.length > 0) {
			return `已选择${selectKeys.length}个店铺`;
		}
		return '请选择店铺';
	}, [selectKeys])

	const GroupShop = (val) => {
		if(val.ecStoreSearchDetailList.length == 0) {
			return null;
		}
		const isOpen = openGroup[val.id] == false ? false : true;
		let selectCount = 0;
		val.ecStoreSearchDetailList.map(v => {
			if (selectKeys.includes(v.ecStoreId)) {
				selectCount = selectCount + 1;
			}
		})
		const indeterminate = (selectCount > 0 && selectCount < val.ecStoreSearchDetailList.length) ? true : false;
		const isChecked = selectCount == val.ecStoreSearchDetailList.length ? true : false;
		return (
			<div>
				<div className={styles.groupName} style={{ background: isChecked ? '#EBF4FF' : '#fff' }}>
					{
						isOpen ?
							<DownOutlined onClick={() => setOpenGroup({ ...openGroup, [val.id]: false })} className={styles.operaIcon} />
							:
							<RightOutlined onClick={() => setOpenGroup({ ...openGroup, [val.id]: true })} className={styles.operaIcon} />
					}
					<Checkbox className="allCheckedStyle" indeterminate={indeterminate} onChange={e => checkGroupAll(e, val.ecStoreSearchDetailList)} checked={isChecked}>{val.groupName}</Checkbox>
				</div>
				<div style={{ marginLeft: '32px', overflow: 'hidden', height: isOpen ? 'auto' : '0px' }}>
					{
						val.ecStoreSearchDetailList.map(k => {
							const isChecked = selectKeys.includes(k.ecStoreId);
							return (
								<div className={styles.shopItem} style={{ background: isChecked ? '#EBF4FF' : '#fff' }} key={k.ecStoreId}>
									<Checkbox checked={isChecked} onChange={e => selectStore(e, k.ecStoreId)} style={{ marginRight: '4px' }}>
										<Tooltip mouseEnterDelay={0.5} title={k.storeName + '-' + platformTypeName[k.type]}>
											<span className="text-overflow" style={{ display: 'inline-block', width: '148px', verticalAlign: 'bottom' }}>{k.storeName + '-' + platformTypeName[k.type]}</span>
										</Tooltip>
									</Checkbox>
								</div>
							)
						})
					}
				</div>
			</div>
		)
	}

	//自定义下拉框渲染
	const dropdownRender = () => {
		return (
			<div className={styles.wrap} id="modal-root">
				<div className={styles.clearWrap}>
					<span className={styles.clearText} onClick={() => setSelectKeys([])}>清空选择</span>
				</div>
				<div className={styles.itemWrap}>
					<Input value={searchStr} onChange={e => setSearchStr(e.target.value)} placeholder="请输入店铺" prefix={<SearchOutlined />} />
					<span onClick={openShopSet}><Iconfont className={styles.setIcon} type='iconshezhi' /></span>
				</div>
				{
					ecStoreSearchGroupList.map(v => {
						return (
							<GroupShop key={v.id} {...v} />
						)
					})
				}
				{
					unGroupedEcStore.map(v => {
						const isChecked = selectKeys.includes(v.id);
						return (
							<div style={{ background: isChecked ? '#EBF4FF' : '#fff' }} className={styles.shopItem} key={v.id}>
								<Checkbox checked={isChecked} onChange={e => selectStore(e, v.id)} style={{ marginRight: '4px' }}>
									<Tooltip mouseEnterDelay={0.5} title={v.storeName + '-' + platformTypeName[v.type]}>
										<span className="text-overflow" style={{ display: 'inline-block', width: '176px', verticalAlign: 'bottom' }}>{v.storeName + '-' + platformTypeName[v.type]}</span>
									</Tooltip>
								</Checkbox>
							</div>
						)
					})
				}
			</div>
		)
	}

	//店铺分组设置弹框
	const SetShopProps = {
		visible,
		handleOk() {
			setVisible(false);
			setOpen(true);
			getShopList();
		},
		handleCancel() {
			setVisible(false);
			setOpen(true);
		}
	}

	return (
		<>
			<Select
			  className={selectKeys.length > 0 ? styles.shopSearchSelect : ''}
				placeholder={placeholder}
				onDropdownVisibleChange={handleVisibleChange}
				open={open}
				dropdownMatchSelectWidth={240}
				dropdownRender={dropdownRender}
				style={style}
			/>
			{visible && <SetShop {...SetShopProps} />}
		</>
	)
}
